package cloud.demarcia.yzcrawler.processors;

import cloud.demarcia.yzcrawler.entities.Profile;
import cloud.demarcia.yzcrawler.utils.Browser;
import cloud.demarcia.yzcrawler.utils.UrlGenerator;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
@Slf4j
public class ProvinceProcessor {

    @Autowired
    private UrlGenerator urlGenerator;

    public List<String> process(String code, Profile profile) {
        String provinceUrl = urlGenerator.getProvince(code, profile);
        List<String> universityNames = new LinkedList<>();
        try {
            Browser browser = new Browser();
            Document document = browser.browse(provinceUrl);
            browser.close();
            Element element = document.getElementsByClass("ch-table").get(0);
            Elements elements = element.child(1).children();
            for (Element element1 : elements) {
                String text = element1.child(0).child(0).child(0).text();
                String s = text.split("\\)")[1];
                universityNames.add(s);
            }
        } catch (Exception e) {
            log.warn("Failed to get universities, province code: " + code);
        }
        return universityNames;
    }
}
